package cloud.seckill.ribbonserver.service;

import cloud.seckill.ribbonserver.config.loadbalancer.LoadBalancer;
import cloud.seckill.ribbonserver.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @title: RibbonService
 * @Author Wangsj
 * @Date: 2021/5/24
 */
@Service
public class RibbonService implements IRibbonService {

    private static final String SERVICE_ID = "seckill";

    private static final String BASE_URL = "http://seckill/";

    @Autowired
    RestTemplate restTemplate;

    /**
     * 引入我们自己写的轮询接口
     */
    @Resource
    private LoadBalancer loadBalancer;

    /**
     * 用来获取服务信息
     */
    @Resource
    private DiscoveryClient discoveryClient;


    List<ServiceInstance> instances = null;

    public String show() {
        return restTemplate.getForObject(getURI() + "test/show", String.class);
    }

    public Result getSeckillResult(String path){
        return restTemplate.getForObject(getURI() + path, Result.class);
    }

    private URI getURI() {

        if (null==instances){
            instances = discoveryClient.getInstances(SERVICE_ID);
        }

        /**判断服务是否存在*/
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        /**获取负载均衡（轮询）后的服务信息*/
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        /**获取服务地址*/
        return serviceInstance.getUri();

    }

}
